package co.fitstart.mobile.dao.support;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.demo2do.core.persistence.GenericDaoSupport;

import co.fitstart.entity.credit.Credit;
import co.fitstart.entity.user.User;

/**
 * @author Guangli Yan
 *
 */
@Repository
public class CreditDaoSupport {

    @Autowired
    private GenericDaoSupport genericDaoSupport;

    /**
     * load credit. If empty, create.
     * 
     * @param user
     * @return
     */
    public Credit generallyLoad(User user) {
        String querySentence = "FROM Credit credit WHERE credit.user = :user";
        Credit credit = genericDaoSupport.searchForObject(querySentence, "user", user, Credit.class);

        if (credit == null && user.getCredit() > 0) {
            credit = new Credit(user);
            genericDaoSupport.save(credit.increaseCredit(user.getCredit()));
        }

        return credit;
    }

}
